<template>
  <view class="login-container">
    <view class="login-content">
      <view class="login-header">
        <text class="title">知医</text>
        <text class="subtitle">智慧医疗服务平台</text>
      </view>
      <view class="login-form">
        <view class="input-group">
          <input type="text" placeholder="请输入用户名" class="input" v-model="username" />
        </view>
        <view class="input-group">
          <input type="password" placeholder="请输入密码" class="input" v-model="password" />
        </view>
        <view class="input-group captcha-group">
          <input type="text" placeholder="请输入验证码" class="input captcha-input" v-model="code" />
          <image :src="captchaImg" class="captcha-img" @tap="getCaptcha" mode="aspectFit"></image>
        </view>
        <button class="login-btn" :loading="loading" @tap="handleLogin">
          {{ loading ? '登录中...' : '登录' }}
        </button>
        <button class="wechat-btn" @tap="handleWxLogin">
          <image src="/static/images/wechat.png" class="wechat-icon" mode="aspectFit"></image>
          微信登录
        </button>
        <view class="register-link" @tap="goToRegister">
          立即注册
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getToken, setToken, removeToken } from '@/utils/auth'
import request from '@/utils/request'

export default {
  data() {
    return {
      username: '',
      password: '',
      code: '',
      uuid: '',
      captchaImg: '',
      loading: false
    }
  },
  onLoad() {
    this.getCaptcha()
  },
  methods: {
    async getCaptcha() {
      try {
        const res = await request({
          url: '/captchaImage',
          method: 'get',
          headers: {
            isToken: false
          }
        })
        if (res.code === 200) {
          this.captchaImg = 'data:image/gif;base64,' + res.img
          this.uuid = res.uuid
        } else {
          uni.showToast({
            title: '获取验证码失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取验证码错误:', error)
        uni.showToast({
          title: '获取验证码失败',
          icon: 'none'
        })
      }
    },
    async handleLogin() {
      if (!this.username || !this.password) {
        uni.showToast({
          title: '请输入用户名和密码',
          icon: 'none'
        })
        return
      }
      if (!this.code) {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none'
        })
        return
      }
      this.loading = true
      try {
        console.log('开始登录请求')
        const res = await request({
          url: '/login',
          method: 'post',
          headers: {
            isToken: false
          },
          data: {
            username: this.username,
            password: this.password,
            code: this.code,
            uuid: this.uuid
          }
        })
        console.log('登录响应:', res)
        
        // 检查响应数据结构
        if (res.code === 200 && res.data && res.data.token) {
          setToken(res.data.token)
          // 获取用户信息
          try {
            const userInfo = await request({
              url: '/getInfo',
              method: 'get'
            })
            if (userInfo.code === 200) {
              uni.showToast({
                title: '登录成功',
                icon: 'success',
                duration: 1500
              })
              setTimeout(() => {
                const pages = getCurrentPages()
                if (pages.length > 1) {
                  uni.navigateBack()
                } else {
                  uni.reLaunch({
                    url: '/pages/index/index'
                  })
                }
              }, 1500)
            } else {
              throw new Error(userInfo.msg || '获取用户信息失败')
            }
          } catch (error) {
            console.error('获取用户信息错误:', error)
            removeToken()
            uni.showToast({
              title: error.message || '获取用户信息失败',
              icon: 'none',
              duration: 2000
            })
          }
        } else if (res.code === 200 && res.token) {
          // 兼容直接返回token的情况
          setToken(res.token)
          // 获取用户信息
          try {
            const userInfo = await request({
              url: '/getInfo',
              method: 'get'
            })
            if (userInfo.code === 200) {
              uni.showToast({
                title: '登录成功',
                icon: 'success',
                duration: 1500
              })
              setTimeout(() => {
                const pages = getCurrentPages()
                if (pages.length > 1) {
                  uni.navigateBack()
                } else {
                  uni.reLaunch({
                    url: '/pages/index/index'
                  })
                }
              }, 1500)
            } else {
              throw new Error(userInfo.msg || '获取用户信息失败')
            }
          } catch (error) {
            console.error('获取用户信息错误:', error)
            removeToken()
            uni.showToast({
              title: error.message || '获取用户信息失败',
              icon: 'none',
              duration: 2000
            })
          }
        } else {
          throw new Error(res.msg || '登录失败：未获取到token')
        }
      } catch (error) {
        console.error('登录错误:', error)
        uni.showToast({
          title: error.message || '登录失败，请重试',
          icon: 'none',
          duration: 2000
        })
        // 登录失败时刷新验证码
        this.getCaptcha()
      } finally {
        this.loading = false
      }
    },
    goToRegister() {
      uni.navigateTo({
        url: '/pages/register/register'
      })
    },
    // 处理微信登录
    async handleWxLogin() {
      // #ifdef MP-WEIXIN
      try {
        const { code } = await uni.login({
          provider: 'weixin'
        });
        
        const res = await request({
          url: '/wxLogin',
          method: 'post',
          data: code,
          headers: {
            isToken: false
          }
        });
        
        if (res.code === 200) {
          // 直接使用返回的token
          const token = res.data;
          setToken(token);
          
          uni.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 1500
          });
          
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/index/index'
            });
          }, 1500);
        } else {
          throw new Error(res.msg || '微信登录失败');
        }
      } catch (error) {
        console.error('微信登录错误:', error);
        uni.showToast({
          title: error.message || '微信登录失败，请重试',
          icon: 'none',
          duration: 2000
        });
      }
      // #endif
      
      // #ifndef MP-WEIXIN
      uni.showToast({
        title: '请在微信小程序中使用微信登录',
        icon: 'none'
      });
      // #endif
    }
  }
}
</script>

<style>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #e6f3ff 0%, #f0f7ff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
}

.login-content {
  width: 100%;
  max-width: 750rpx;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 24rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.05);
  padding: 60rpx 40rpx;
  box-sizing: border-box;
}

.login-header {
  text-align: center;
  margin-bottom: 60rpx;
}

.title {
  font-size: 56rpx;
  font-weight: bold;
  color: #2c3e50;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.subtitle {
  display: block;
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #7f8c8d;
}

.login-form {
  width: 100%;
}

.input-group {
  margin-bottom: 30rpx;
  background-color: #f8fafc;
  border-radius: 16rpx;
  padding: 24rpx;
  border: 2rpx solid #e8f0fe;
  transition: all 0.3s ease;
}

.input-group:focus-within {
  border-color: #007AFF;
  box-shadow: 0 0 0 2rpx rgba(0, 122, 255, 0.1);
}

.input {
  height: 80rpx;
  font-size: 28rpx;
  color: #2c3e50;
}

.input::placeholder {
  color: #95a5a6;
}

.captcha-group {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.captcha-input {
  flex: 1;
}

.captcha-img {
  width: 200rpx;
  height: 80rpx;
  border-radius: 8rpx;
  background: #fff;
}

.login-btn {
  margin-top: 60rpx;
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background: linear-gradient(135deg, #007AFF 0%, #0056b3 100%);
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.2);
  transition: all 0.3s ease;
}

.login-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 2rpx 6rpx rgba(0, 122, 255, 0.2);
}

.wechat-btn {
  margin-top: 20rpx;
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background: #07c160;
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(7, 193, 96, 0.2);
  transition: all 0.3s ease;
}

.wechat-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 2rpx 6rpx rgba(7, 193, 96, 0.2);
}

.wechat-icon {
  width: 48rpx;
  height: 48rpx;
  margin-right: 16rpx;
}

.register-link {
  text-align: right;
  font-size: 28rpx;
  color: #007AFF;
  margin-top: 30rpx;
  padding-right: 20rpx;
  opacity: 0.9;
  transition: opacity 0.3s ease;
}

.register-link:active {
  opacity: 0.7;
}
</style> 